package com.axend.aerosense.room.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.IComplete;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.bean.PersonSelectItemBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.room.ui.activity.PeoplePickerActivity;
import com.axend.aerosense.room.ui.adapter.PersonProviderMultiAdapter;
import com.axend.aerosense.room.viewmodel.RoomPersonViewModel;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomFragmentEmergencyContactSettingBinding;
import com.axend.aerosense.room.entity.PersonListResult;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 监护人,紧急联系人列表界面,用户在此选择监护人(非新增界面)
 */
public class RoomPersonSelectFragment extends MvvmBaseFragment<RoomFragmentEmergencyContactSettingBinding, RoomPersonViewModel>
        implements ILoadDataResult<PersonListResult>, IComplete {
    private PersonProviderMultiAdapter adapter;
    private ArrayList<PersonSelectItemBean> emergencyInfo = new ArrayList<PersonSelectItemBean>();
    // 是否为选择模式
    boolean selectMode = false;
    // 已经选择的联系人
    String uuid = null;
    private PersonSelectItemBean selectPerson = null;
    public final static String ROOM_TYPE = "ROOM_TYPE";
    public final static String UUID = "UUID";
    public final static String SELECT_PERSON = "selectPerson";

    public static RoomPersonSelectFragment getInstance(boolean selectMode, String uid){
        RoomPersonSelectFragment fragment = new RoomPersonSelectFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(ROOM_TYPE, selectMode);
        bundle.putString(UUID, uid);
        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    protected void initParameters() {
        super.initParameters();
        Bundle bundle = getArguments();
        if(null != bundle){
            selectMode = bundle.getBoolean(ROOM_TYPE, false);
            uuid = bundle.getString(UUID);
        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.PERSON_COUNT_CHANGE ,Integer.class)
                .observe(getViewLifecycleOwner(), bean-> {
                    viewModel.onLoad();
                });
    }

    @Override
    public void onResume() {
        super.onResume();

        if(selectMode){
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.room_emergency2));
//            ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_complete));
            ((PeoplePickerActivity)getActivity()).setRightTitle("");
            if(null == selectPerson){
                ((PeoplePickerActivity)getActivity()).setRightTitleClickable(false);
            }else{
                ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
            }

        }else{
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.room_emergency));
            ((PeoplePickerActivity)getActivity()).setRightTitle("");
        }
    }

    private void initView() {
        setLoadSir(viewDataBinding.roomFragmentConent);
        showLoading();
        viewModel.onLoad();
        adapter = new PersonProviderMultiAdapter(selectMode);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        viewDataBinding.roomPersonRecyclerview.setLayoutManager(layoutManager);
        viewDataBinding.roomPersonRecyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, view, position) -> {

            PersonSelectItemBean person = (PersonSelectItemBean) adapter.getData().get(position);
            String uid = person.getEmergencyUuid();
            if(selectMode){
                boolean tmp = person.isSelecte();
                for(PersonSelectItemBean personSelectItemBean : (List<PersonSelectItemBean>)adapter.getData()){
                    personSelectItemBean.setSelecte(false);
                }
                if(tmp){
                    selectPerson = null;
                    ((PeoplePickerActivity)getActivity()).setRightTitleClickable(false);
                }else{
                    person.setSelecte(true);
                    selectPerson = person;
                    ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
                }

                adapter.notifyDataSetChanged();

            }else{
                changeFragment(RoomPersonSettingFragment.getInstance(uid));
            }
        });
        viewDataBinding.roomAdd.setOnClickListener(v->{
            changeFragment(RoomPersonSettingFragment.getInstance(null));
        });
    }
    private void changeFragment(Fragment fragment){
        FragmentUtil.add(getActivity(), ((PeoplePickerActivity)getActivity()).getContentId(),fragment, this, true);
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_fragment_emergency_contact_setting;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected RoomPersonViewModel getViewModel() {
        BaseViewModelFactroy<PersonListResult> baseViewModelFactroy = new BaseViewModelFactroy<PersonListResult> (this, this);
        return new ViewModelProvider(this, baseViewModelFactroy).get(RoomPersonViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void loadDataSuccess(PersonListResult personBean) {
        selectPerson = null;
        if(null != emergencyInfo && emergencyInfo.size()>0){
            emergencyInfo.clear();
        }
        emergencyInfo.addAll(personBean.emergencyInfo);
        if(selectMode){
            ((PeoplePickerActivity)getActivity()).setRightTitleClickable(false);
            if(!TextUtils.isEmpty(uuid)){
                for(PersonSelectItemBean bean :emergencyInfo){
                    if(bean.getEmergencyUuid().equals(uuid)){
                        selectPerson = bean;
                        bean.setSelecte(true);
                        break;
                    }
                }
            }
        }

        adapter.setList(emergencyInfo);
        if(selectMode && null != selectPerson){
            ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
        }
    }

    @Override
    public void loadDataFail(String decs) {
        ToastUtils.showLong(decs);
        showEmpty();
    }

    @Override
    public void complete() {
        // 工具栏完成事件
        if(selectMode){
            if(selectPerson != null){
                Intent data = new Intent();
                data.putExtra(SELECT_PERSON, selectPerson);
                getActivity().setResult(RoomSettingFragment.REQUEST_PERSON, data);
            }
            getActivity().finish();
        }
    }
}
